package com.tianxinweb.utils;

import com.tianxinweb.enums.ResultEnum;
import com.tianxinweb.exception.MyException;
import org.apache.http.client.fluent.Request;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * Created by cboy on 2018/5/3.
 */
public class ImageUtil {

    /**
     * 保存网路图片
     * @param url
     * @param path
     */
    public static void saveImage(String url,String path){
        File file = new File(path);
        if(!file.getParentFile().exists()){
            file.getParentFile().mkdirs();
        }
        try {
            Request.Get(url).execute().saveContent(file);
        }catch (Exception e){
            throw new MyException(ResultEnum.FAILE);
        }

    }

    /**
     * 移动图片到其他目录
     * @param source
     * @param target
     */
    public static String moveFile(String source,String target){
        File sFile = new File(source);
        if(!sFile.exists()) throw new MyException(ResultEnum.FILE_NOT_EXISTS);
        String suffix = source.substring(source.lastIndexOf("."),source.length());
        String filename = new SimpleDateFormat("yyyyMMdd").format(new Date())+"/"+ UUID.randomUUID().toString()+suffix;
        File tFile = new File(target,filename);
        if(!tFile.getParentFile().exists()){
            tFile.getParentFile().mkdirs();
        }
        sFile.renameTo(tFile);
        return filename;
    }
}
